7.11.2 型switch
型switchはインタフェースが複数の型のいずれかである場合に使用する
code:go
func doThings(i any) {
switch j := i.(type) {
case nil: // iはnil。jの型はany
fmt.Printf(" case nil; i:%v(型:%T), j:%v(型:%T)\n", i, i, j, j)
case int: // jの型はint
fmt.Printf(" case int; i:%d(型:%T), j:%v(型:%T)\n", i, i, j, j)
case MyInt: // jの型はMyInt
fmt.Printf(" case MyInt; i:%d(型:%T), j:%v(型:%T)\n", i, i, j, j)
case io.Reader: // jの型はio.Reader
fmt.Printf(" case io.Reader; i:%v(型:%T), j:%v(型:%T)\n", i, i, j, j)
case string: // jは文字列
fmt.Printf(" case string; i:%s(型:%T), j:%v(型:%T)\n", i, i, j, j)
case bool, rune: // iはboonかruneなので、jの型はany
fmt.Printf(" case bool, rune; i:%v(型:%T), j:%v(型:%T)\n", i, i, j, j)
default: // iの型は不明。jの型はany
fmt.Printf(" default; i:%v(型:%T), j:%v(型:%T)\n", i, i, j, j)
}
}